package model

import "github.com/jinzhu/gorm"

type (
	LedgerDevices []*LedgerDevice

	LedgerDevice struct {
		Model
		LedgerID uint   `json:"ledger_id" gorm:"column:ledger_id;not null;"`
		DeviceID uint   `json:"device_id" gorm:"column:device_id;not null;"`
		DeviceNo string `json:"device_no" gorm:"column:device_no;size:255;not null;default:''"`

		Device *Device `json:"device" gorm:"-"`
	}
)

func GetLedgerDevicesByLedgerID(ledgerID uint) (LedgerDevices, error) {
	ledgerDevices := make(LedgerDevices, 0)
	if err := db.Model(&LedgerDevice{}).Where("ledger_id = ?", ledgerID).First(&ledgerDevices).Error; err != nil {
		return nil, err
	}

	for _, ld := range ledgerDevices {
		device, err := GetDevice(int(ld.DeviceID))
		if err != nil {
			return nil, err
		}
		ld.Device = device
	}

	return ledgerDevices, nil
}

func AddLedgerDevices(ledgerDevices LedgerDevices, tx *gorm.DB) error {
	for _, device := range ledgerDevices {
		if err := tx.Create(device).Error; err != nil {
			return err
		}
	}
	return nil
}

func DeleteLedgerDevicesByLedgerID(ledgerID int, tx *gorm.DB) error {
	if err := tx.Delete(&LedgerDevice{}, "ledger_id = ?", ledgerID).Error; err != nil {
		return err
	}
	return nil
}

func (ld LedgerDevices) ToMap() map[int]*LedgerDevice {
	m := make(map[int]*LedgerDevice)
	for _, ldRel := range ld {
		m[int(ldRel.ID)] = ldRel
	}
	return m
}
